const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { body, validationResult } = require('express-validator');
const { authenticateToken, generateString, encryptPhone, decryptPhone, extractNumber, getNextId, logUserOperation } = require('../untils/untils');
const dayjs = require('dayjs')
const { cryptoHelper } = require('../config/global');
const fs = require('fs');
const path = require('path');

// 获取消费记录
// { "cust_id": "", "consume_time": [ "2025-07-01 01:14:06", "2025-07-10 01:17:04" ] }
router.get('/', authenticateToken, async (req, res) => {
    try {
        const { cust_id, consume_time } = req.query;
        let sql = 'SELECT * FROM consumption';

        if (cust_id) {
            sql += ` AND cust_id = '${cust_id}'`;
        }
        if (consume_time) {
            sql += ` AND consume_time >= '${consume_time[0]}' AND consume_time <= '${consume_time[1]}'`;
        }

        // 获取客户信息
        const [customer] = await db.execute('SELECT * FROM customer',);
        // 获取消费项目
        const [project] = await db.execute('SELECT * FROM project',);

        let [result] = await db.execute(sql);

        result.forEach(item => {
            item.cust_name = customer.find(customer => customer.cust_id === item.cust_id).cust_name;
            item.project_name = project.find(project => project.project_id === item.project_id).project_name;
            item.consume_time = dayjs(item.consume_time).format('YYYY-MM-DD HH:mm:ss');
        });

        await logUserOperation(req, '查询', '获取消费记录', '获取消费记录成功', '成功');
        res.json({
            success: true,
            message: '获取预约记录成功',
            data: result
        });
    } catch (error) {
        console.error('获取预约记录失败:', error);
        await logUserOperation(req, '查询', '获取消费记录', '获取消费记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '获取预约记录失败',
            error: error.message
        });
    }
});

// 新增消费记录
// { "cust_id": "C00001", "project_id": "PR00002", "consume_time": "2025-07-11 22:03:33", "amount": 132, "payment": "支付宝", "notes": "123", "attachment": [ "1752242605446mxluh" ] }
router.put("/add", authenticateToken, async (req, res) => {
    try {
        const { cust_id, project_id, consume_time, amount, payment, notes, attachment } = req.body;

        // 根据项目获取价格
        const [project] = await db.execute('SELECT * FROM project WHERE project_id = ?', [project_id]);
        const price = project[0].price || 0;

        const consume_id = await getNextId('CUS', 'consume_id', 'consumption', 5);
        let sql = `INSERT INTO consumption (consume_id, cust_id, notes, project_id, attachment,amount,payment,consume_time,price) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)`;
        let params = [consume_id, cust_id, notes, project_id, attachment, amount, payment, consume_time, price];

        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '添加', '新增消费记录', '新增消费记录成功', '成功');
        // 获取用户信息
        const [user] = await db.execute('SELECT * FROM user WHERE username = ?', [req.user.userId]);
        const emp_id = user[0].emp_id;

        // 调用回访记录表新增接口
        const plan_date = dayjs().add(3, 'day').format('YYYY-MM-DD HH:mm:ss');
        const status = '待跟进';
        const task_id = await getNextId('RV', 'task_id', 'revisit_task', 5);
        const sql_revisit_task = `INSERT INTO revisit_task (task_id, cust_id, consume_id, emp_id, plan_date, status) VALUES (?, ?, ?, ?, ?, ?)`;
        const params_revisit_task = [task_id, cust_id, consume_id, emp_id, plan_date, status];
        await db.execute(sql_revisit_task, params_revisit_task);

        res.json({
            success: true,
            message: '新增消费记录成功',
            data: result
        });
    } catch (error) {
        console.error('新增消费记录失败:', error);
        await logUserOperation(req, '添加', '新增消费记录', '新增消费记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '新增消费记录失败',
            error: error.message
        });
    }
});

// 更新消费记录
router.post("/update", authenticateToken, async (req, res) => {
    try {
        const { cust_id, notes, project_id, consume_id, amount } = req.body;
        let sql = `UPDATE consumption SET cust_id = ?, notes = ?, project_id = ?, amount = ? WHERE consume_id = ?`;

        // 根据项目获取价格
        const [project] = await db.execute('SELECT * FROM project WHERE project_id = ?', [project_id]);
        const price = project[0].price || 0;

        let params = [cust_id, notes, project_id, amount, consume_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '更新', '更新消费记录', '更新消费记录成功', '成功');
        res.json({
            success: true,
            message: '更新消费记录成功',
            data: result
        });
    } catch (error) {
        console.error('更新消费记录失败:', error);
        await logUserOperation(req, '更新', '更新消费记录', '更新消费记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '更新消费记录失败',
            error: error.message
        });
    }
});

// 删除消费记录
router.delete("/delete", authenticateToken, async (req, res) => {
    try {
        const { consume_id } = req.query;
        let sql = `DELETE FROM consumption WHERE consume_id = ?`;
        let params = [consume_id];
        const [result] = await db.execute(sql, params);
        await logUserOperation(req, '删除', '删除消费记录', '删除消费记录成功', '成功');
        res.json({
            success: true,
            message: '删除消费记录成功',
            data: result
        });
    } catch (error) {
        console.error('删除消费记录失败:', error);
        await logUserOperation(req, '删除', '删除消费记录', '删除消费记录失败', '失败', error.message);
        res.status(500).json({
            success: false,
            message: '删除消费记录失败',
            error: error.message
        });
    }
});

// 获取客户表数据
router.get("/getCustomerInfo", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT * FROM customer`;
        let [result] = await db.execute(sql);
        result = result.map(item => {
            return {
                key: item.cust_id,
                name: item.cust_name
            }
        });
        res.json({
            success: true,
            message: '获取客户信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取客户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取客户信息失败',
            error: error.message
        });
    }
});

// 获取项目表数据
router.get("/getProject", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT project_id as 'key', project_name as 'name' FROM project`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取项目信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取项目信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取项目信息失败',
            error: error.message
        });
    }
});

// 获取支付方式
router.get("/getPaymentMethod", authenticateToken, async (req, res) => {
    // '微信','支付宝','银联卡','现金'
    let payment_method = [
        {
            key: '微信',
            name: '微信'
        },
        {
            key: '支付宝',
            name: '支付宝'
        },
        {
            key: '银联卡',
            name: '银联卡'
        },
        {
            key: '现金',
            name: '现金'
        }
    ]
    res.json({
        success: true,
        message: '获取支付方式成功',
        data: payment_method
    });
});

// 获取用户表数据
router.get("/getEmployee", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT emp_id as 'key', emp_name as 'name' FROM employee`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取用户信息成功',
            data: result
        });
    } catch (error) {
        console.error('获取用户信息失败:', error);
        res.status(500).json({
            success: false,
            message: '获取用户信息失败',
            error: error.message
        });
    }
});

// 获取查询项客户list
router.get("/getCustomerList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT consumption.cust_id as 'key', customer.cust_name as 'name' FROM consumption LEFT JOIN customer ON consumption.cust_id = customer.cust_id`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取客户列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取客户列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取客户列表失败',
            error: error.message
        });
    }
});

// 获取查询项预约项目
router.get("/getProjectIdList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT consumption.project_id as 'key', project.project_name as 'name' FROM consumption LEFT JOIN project ON consumption.project_id = project.project_id`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取预约项目成功',
            data: result
        });
    } catch (error) {
        console.error('获取预约项目失败:', error);
        res.status(500).json({
            success: false,
            message: '获取预约项目失败',
            error: error.message
        });
    }
});

// 获取查询项员工list
router.get("/getEmployeeList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT consumption.emp_id as 'key', employee.emp_name as 'name' FROM consumption LEFT JOIN employee ON consumption.emp_id = employee.emp_id`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取员工列表成功',
            data: result
        });
    } catch (error) {
        console.error('获取员工列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取员工列表失败',
            error: error.message
        });
    }
});

// 获取查询项预约状态
router.get("/getAppointmentStatusList", authenticateToken, async (req, res) => {
    try {
        let sql = `SELECT DISTINCT status as 'key', status as 'name' FROM appointment`;
        let [result] = await db.execute(sql);
        res.json({
            success: true,
            message: '获取预约状态成功',
            data: result
        });
    } catch (error) {
        console.error('获取预约状态失败:', error);
        res.status(500).json({
            success: false,
            message: '获取预约状态失败',
            error: error.message
        });
    }
});

// 文件上传
// 将上传的文件写入到uploadField文件夹下
router.post("/upload", authenticateToken, async (req, res) => {
    try {
        console.log('🔍 请求体:', req.body);
        console.log('🔍 文件对象:', req.files);
        console.log('🔍 文件类型:', typeof req.files);

        if (!req.files || !req.files.file) {
            console.log('❌ 没有找到文件');
            return res.status(400).json({
                success: false,
                message: '没有上传文件'
            });
        }

        const file = req.files.file;
        console.log('🔍 文件详情:', {
            name: file.name,
            size: file.size,
            mimetype: file.mimetype,
            data: typeof file.data,
            dataLength: file.data ? file.data.length : 'undefined',
            tempFilePath: file.tempFilePath,
            mv: typeof file.mv
        });

        // 检查文件数据 - 修复版本
        if (!file.data && !file.tempFilePath) {
            console.log('❌ 文件数据为空');
            return res.status(400).json({
                success: false,
                message: '文件数据为空'
            });
        }

        // 验证文件类型
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        if (!allowedTypes.includes(file.mimetype)) {
            return res.status(400).json({
                success: false,
                message: '不支持的文件类型，只支持 JPG、PNG、GIF、PDF'
            });
        }

        // 验证文件大小（5MB）
        if (file.size > 5 * 1024 * 1024) {
            return res.status(400).json({
                success: false,
                message: '文件大小不能超过5MB'
            });
        }

        // 创建上传目录
        const uploadDir = path.join(__dirname, '../public/uploadField');
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
            console.log('📁 创建上传目录:', uploadDir);
        }



        // 生成唯一文件名
        /* 
        CREATE TABLE `file_info` (
            `id` int NOT NULL AUTO_INCREMENT,
            `file_id` varchar(50) NOT NULL,
            `file_name` varchar(255) NOT NULL,
            `file_path` varchar(500) NOT NULL,
            `file_size` bigint NOT NULL,
            `upload_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `upload_user_id` varchar(50) DEFAULT NULL,
            `status` tinyint DEFAULT '1',
            PRIMARY KEY (`id`),
            UNIQUE KEY `file_id` (`file_id`),
            KEY `idx_file_id` (`file_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
        
        */
        // 文件id 作为新文件名 生成一个5位随机字符串 不能用generateString 
        const file_id = Date.now() + Math.random().toString(36).substring(2, 7);
        // 原文件名
        const file_name = file.name;
        // 文件后缀
        const file_extension = path.extname(file_name);
        // 文件路径
        const file_path = path.join(uploadDir, file_id + file_extension);
        // 文件大小
        const file_size = file.size;
        // 上传时间
        const upload_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
        // 上传用户id
        const upload_user_id = req.user.userId;
        // 状态
        const status = 1;
        // 保存文件到磁盘
        await file.mv(file_path);
        console.log('💾 文件已保存到:', file_path);

        // 生成 base64（可选，用于前端预览）
        let base64 = '';
        if (file.data) {
            base64 = file.data.toString('base64');
        } else if (file.tempFilePath) {
            // 如果文件在临时路径，读取文件内容
            const fileBuffer = fs.readFileSync(file.tempFilePath);
            base64 = fileBuffer.toString('base64');
        }
        console.log('🔍 Base64长度:', base64.length);

        // 保存文件信息到数据库（可选）
        const fileRecord = {
            file_extension: file_extension,
            file_id: file_id,
            file_name: file_name,
            file_path: file_path,
            file_size: file_size,
            upload_time: upload_time,
            upload_user_id: upload_user_id,
            status: status
        };

        // 将图片信息保存到数据库
        let sql = `INSERT INTO file_info (file_extension, file_id, file_name, file_path, file_size, upload_time, upload_user_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
        let params = [file_extension, file_id, file_name, file_path, file_size, upload_time, upload_user_id, status];
        const [result] = await db.execute(sql, params);

        res.json({
            success: true,
            message: '文件上传成功',
            data: {
                file_extension: fileRecord.file_extension,
                file_id: fileRecord.file_id,
                file_name: fileRecord.file_name,
                file_path: fileRecord.file_path,
                file_size: fileRecord.file_size,
                upload_time: fileRecord.upload_time,
                upload_user_id: fileRecord.upload_user_id,
                status: fileRecord.status,
                base64: base64, // 可选，用于前端预览
                showImage: `/consumption/showImage/${fileRecord.file_id}${fileRecord.file_extension}`,
                download_url: `/consumption/download/${fileRecord.file_id}${fileRecord.file_extension}` // 下载链接
            }
        });
    } catch (error) {
        console.error('文件上传失败:', error);
        res.status(500).json({
            success: false,
            message: '文件上传失败',
            error: error.message
        });
    }
});

// 文件下载
router.get("/download/:fileId", authenticateToken, async (req, res) => {
    try {
        const { fileId } = req.params;

        // 这里应该从数据库查询文件信息
        // const [files] = await db.execute(
        //     'SELECT * FROM file_uploads WHERE file_id = ?',
        //     [fileId]
        // );

        // 临时实现：根据文件ID查找文件
        const uploadDir = path.join(__dirname, '../public/uploadField');
        const files = fs.readdirSync(uploadDir);
        const targetFile = files.find(file => file.startsWith(fileId.replace('F', '')));

        if (!targetFile) {
            return res.status(404).json({
                success: false,
                message: '文件不存在'
            });
        }

        const filePath = path.join(uploadDir, targetFile);

        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            return res.status(404).json({
                success: false,
                message: '文件不存在'
            });
        }

        // 设置响应头
        res.setHeader('Content-Type', 'application/octet-stream');
        res.setHeader('Content-Disposition', `attachment; filename="${targetFile}"`);

        // 发送文件
        res.sendFile(filePath);

    } catch (error) {
        console.error('文件下载失败:', error);
        res.status(500).json({
            success: false,
            message: '文件下载失败',
            error: error.message
        });
    }
});

// 获取文件列表
router.get("/files", authenticateToken, async (req, res) => {
    try {
        const uploadDir = path.join(__dirname, '../public/uploadField');

        // 创建一个以用户名命名的文件夹
        const userDir = path.join(uploadDir, req.user.userId);
        if (!fs.existsSync(userDir)) {
            fs.mkdirSync(userDir, { recursive: true });
        }

        // 再创建一个以日期命名的文件夹
        const dateDir = path.join(userDir, dayjs().format('YYYY-MM-DD'));
        if (!fs.existsSync(dateDir)) {
            fs.mkdirSync(dateDir, { recursive: true });
        }

        const files = fs.readdirSync(dateDir);
        const fileList = files.map(file => {
            const filePath = path.join(dateDir, file);
            const stats = fs.statSync(filePath);

            return {
                file_name: file,
                file_size: stats.size,
                upload_time: stats.mtime,
                download_url: `/consumption/download/${file}`,
                showImage: `/consumption/showImage/${file}`
            };
        });

        res.json({
            success: true,
            message: '获取文件列表成功',
            data: fileList
        });

    } catch (error) {
        console.error('获取文件列表失败:', error);
        res.status(500).json({
            success: false,
            message: '获取文件列表失败',
            error: error.message
        });
    }
});

// 显示图片
router.get("/showImage/:fileId", async (req, res) => {
    try {
        const { fileId } = req.params;
        // 根据id查询文件信息   
        const [fileInfo] = await db.execute(
            'SELECT * FROM file_info WHERE file_id = ?',
            [fileId]
        );
        const filePath = path.join(__dirname, '../public/uploadField', fileInfo[0].file_id + fileInfo[0].file_extension);
        res.sendFile(filePath);
    } catch (error) {
        console.error('显示图片失败:', error);
        res.status(500).json({
            success: false,
            message: '显示图片失败',
            error: error.message
        });
    }
});

module.exports = router;